package megrez.mail.sender;

import java.util.Date;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import lombok.RequiredArgsConstructor;
import megrez.mail.sender.common.MailSenderBean;
import megrez.mail.sender.common.MailSenderException;
import megrez.mail.sender.common.MailSenderService;


/**
 * Java邮件发送服务
 * 
 * @author Lucky Yang
 * @since 2.6.9
 */
@RequiredArgsConstructor
public class JavaMailSenderService implements MailSenderService {
    @Value("${spring.mail.username}")
    private String sendMailer;

    private final JavaMailSender javaMailSender;

    @Override
    public void send(MailSenderBean bean) {
        bean.validate();

        try {
            if (bean.isTextable()) {
                sendSimpleMail(bean);
            } else {
                sendHtmlMail(bean);
            }
        } catch (Exception e) {
            throw new MailSenderException(e);
        }
    }

    protected void sendSimpleMail(MailSenderBean bean) {
        SimpleMailMessage message = new SimpleMailMessage();
        // 邮件发件人
        message.setFrom(sendMailer);
        // 邮件收件人 1或多个
        message.setTo(bean.getMailAddresses().toArray(new String[0]));
        // 邮件主题
        message.setSubject(bean.getSubject());
        // 邮件内容
        message.setText(bean.getBody());
        // 邮件发送时间
        message.setSentDate(new Date());

        javaMailSender.send(message);
    }

    protected void sendHtmlMail(MailSenderBean bean) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        // 邮件发件人
        helper.setFrom(sendMailer);
        // 邮件收件人 1或多个
        helper.setTo(bean.getMailAddresses().toArray(new String[0]));
        // 邮件主题
        helper.setSubject(bean.getSubject());
        // 邮件内容
        helper.setText(bean.getBody(), true);
        // 邮件发送时间
        helper.setSentDate(new Date());

        javaMailSender.send(message);
    }

}
